import os
import random
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
from api_key.model import ApiKey
from api_key import get_api_key_by_key

import sha
import random

def generate_api_key(name, email):
    sh = sha.new()
    sh.update(str(name))
    sh.update(str(email))
    sh.update("%s" % random.random())
    sh.update("%s" % random.random())
    return sh.hexdigest()    

def generate_secret_key(name, email):
    sh = sha.new()
    sh.update(str(name))
    sh.update(str(email))
    sh.update(generate_api_key(name, email))
    sh.update("%s" % random.random())
    sh.update("%s" % random.random())
    return sh.hexdigest()    

class ApiKeyManagement(webapp.RequestHandler):
    def get(self):
        template_values = {}
        path = os.path.join(os.path.dirname(__file__), 'index.html')
        self.response.out.write(template.render(path, template_values))

class ListApiKey(webapp.RequestHandler):
    def get(self):
        apis = ApiKey.all()
        template_values = {
            'apis': apis,
        }
        
        path = os.path.join(os.path.dirname(__file__), 'list.html')
        self.response.out.write(template.render(path, template_values))
        
class AddApiKey(webapp.RequestHandler):
    def get(self):
        #key = self.request.get('added')
        # TODO api = find api_key where __key__ = key
        #api = get_api_key_by_key(key)
        #apis = ApiKey.all().fetch(100)

        template_values = {
            #'api' : api,     
            #'apis': apis,       
        }

        path = os.path.join(os.path.dirname(__file__), 'add.html')
        self.response.out.write(template.render(path, template_values))

    def post(self):
        api = ApiKey()
        api.name = self.request.get('api_name').decode('utf-8')
        api.email = self.request.get('api_email').decode('utf-8')
        api.enabled = True if self.request.get('api_enabled') == 'on' else False
        api.api_key = generate_api_key(api.name, api.email)
        api.secret_key = generate_secret_key(api.name, api.email)
        api.put()

        #self.redirect('/api_key/add?added=%s' % api.key(), True)
        self.redirect('/api_key/list', True)
        
class DeleteApiKey(webapp.RequestHandler):
    def get(self):
        key = self.request.get('key')
        ApiKey.delete(ApiKey.get(key))
        self.redirect('/api_key/list', True)
        
class EditApiKey(webapp.RequestHandler):
    def post(self):
        api = get_api_key_by_key(self.request.get('key'))
        api.api_key = self.request.get('api_key')
        api.secret_key = self.request.get('secret_key')
        api.name = self.request.get('name')
        api.email = self.request.get('email')
        api.enabled = True if self.request.get('api_enabled') == 'on' else False
        api.put()
        self.redirect('/api_key/list', True)
        
    def get(self):
        key = self.request.get('key')
        api = get_api_key_by_key(key)        
        template_values = {
            'key': key,
            'api': api,
        }

        path = os.path.join(os.path.dirname(__file__), 'edit.html')
        self.response.out.write(template.render(path, template_values))

class SearchApiKey(webapp.RequestHandler):    
    def post(self):
        searched_api_keys = []
        apis = ApiKey.all()
        keyword = self.request.get('keyword')
        search_type = self.request.get('search_type')
        
        for api in apis:
            if search_type == "name":
                if api.name.find(keyword.strip()) != -1:
                    searched_api_keys.append(api)
            elif search_type == "email":
                if api.email.find(keyword.strip()) != -1:
                    searched_api_keys.append(api)
        
        template_values = {
            'apis': searched_api_keys,
        }

        path = os.path.join(os.path.dirname(__file__), 'list.html')
        self.response.out.write(template.render(path, template_values))     
        
    def get(self):
        template_values = {}
        path = os.path.join(os.path.dirname(__file__), 'search.html')
        self.response.out.write(template.render(path, template_values))
        